package com.xtoad.ecms.common.web.interceptor;

import com.xtoad.ecms.common.web.base.Result;
import com.xtoad.ecms.common.web.annotation.ResponseAdvice;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局请求结果处理
 *
 * @author xtoad
 * @date 2021/02/16
 */
@RestControllerAdvice
public class GlobalResponseInterceptor implements ResponseBodyAdvice {

    /**
     * 判断是否需要进行结果增强
     *
     * @param returnType    the return type
     * @param converterType the selected converter type
     * @return 结果
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        // 检查方法上或者类上的注解是否存在
        if (returnType.getMethod().isAnnotationPresent(ResponseAdvice.class)) {
            // 方法上存在注解，以方法的注解为准
            ResponseAdvice responseAdvice = returnType.getMethod().getAnnotation(ResponseAdvice.class);
            return responseAdvice.value();
        } else if (returnType.getDeclaringClass().isAnnotationPresent(ResponseAdvice.class)) {
            // 若只有类上存在注解，以类上的注解为准
            ResponseAdvice responseAdvice = returnType.getDeclaringClass().getAnnotation(ResponseAdvice.class);
            return responseAdvice.value();
        } else {
            // 类和方法都不存在注解
            return false;
        }
    }

    /**
     * 统一拦截返回结果
     *
     * @param body                  the body to be written
     * @param returnType            the return type of the controller method
     * @param selectedContentType   the content type selected through content negotiation
     * @param selectedConverterType the converter type selected to write to the response
     * @param request               the current request
     * @param response              the current response
     * @return 结果
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType
            , Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 统一返回结果ResultDTO
        return body instanceof Result ? body : Result.success(body);
    }
}
